package com.chuangke.admin.data.builder;

import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chuangke.admin.entity.SysDept;
import com.chuangke.admin.service.SysDeptService;
import com.chuangke.common.data.builder.BuilderConstant;
import com.chuangke.common.data.builder.DataBuildConfig;
import com.chuangke.common.data.builder.IDataBuilder;
import com.chuangke.common.utils.SpringContextUtil;

import cn.hutool.core.util.StrUtil;

public class DeptDataBuilder implements IDataBuilder<SysDept> {

	private static final Logger logger = LoggerFactory.getLogger(DeptDataBuilder.class);

	public static final String NAME = "sys-dept-builder";

	private final String dataType;

	public DeptDataBuilder() {
		this(BuilderConstant.DATA_TYPE_BEAN);
	}

	public DeptDataBuilder(String dataType) {
		this.dataType = dataType;
	}

	@Override
	public String getName() {
		return NAME;
	}

	@Override
	public Map<String, SysDept> getMetaData() {
		SysDeptService sysDeptService = SpringContextUtil.getBean(SysDeptService.class);
		return sysDeptService.findMap();
	}

	@Override
	public void build(Object obj, Map<String, SysDept> metaData, List<DataBuildConfig> dataBuildConfigList) {
		if (metaData == null)
			return;
		try {
			for (DataBuildConfig dataBuildBean : dataBuildConfigList) {
				if (BuilderConstant.DATA_TYPE_BEAN.equals(dataType)) {
					String id = BeanUtils.getProperty(obj, dataBuildBean.getIdColumn());
					if (StrUtil.isBlank(id)) {
						continue;
					}
					SysDept dept = metaData.get(id);
					String value = dept == null ? "" : dept.getName();
					BeanUtils.setProperty(obj, dataBuildBean.getNameColumn(), value);
				} else {
					@SuppressWarnings("unchecked")
					Map<String, Object> objMap = (Map<String, Object>) obj;
					String id = objMap.get(dataBuildBean.getIdColumn()).toString();
					if (StrUtil.isBlank(id)) {
						continue;
					}
					SysDept dept = metaData.get(id);
					String value = dept == null ? "" : dept.getName();
					objMap.put(dataBuildBean.getNameColumn(), value);
				}
			}
		} catch (Exception e) {
			logger.error("设置字段信息出错", e);
		}
	}

}